package com.csdj.t309springboot.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * 语言包
 */
public class MessageLangUtil {

    private static Map<String,ResourceBundle> langMap = new HashMap<>();


    /**
     * 读取语言包
     * @param name
     * @param lang
     * @return
     */
    public static ResourceBundle readBundle(String name,String lang){
        return ResourceBundle.getBundle(name, Locale.forLanguageTag(lang));
    }


    public static String getMsg(int code,String lang){
        ResourceBundle resourceBundle = langMap.get(lang);
        if(resourceBundle == null){
            resourceBundle = readBundle("message",lang);
            langMap.put(lang,resourceBundle);
        }
        return resourceBundle.getString(String.valueOf(code));
    }

    public static String getMsg(int code){
        //获取当前线程的请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String langHeader = request.getHeader("Accept-Language");
        String lang = langHeader.split(",")[0];
        ResourceBundle resourceBundle = langMap.get(lang);
        if(resourceBundle == null){
            resourceBundle = readBundle("message",lang);
            langMap.put(lang,resourceBundle);
        }
        return resourceBundle.getString(String.valueOf(code));
    }


    public static void main(String[] args) {
        String msg = getMsg(0,"vi");
        System.out.println(msg);
    }
}